package com.king.utils;

import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.king.exception.DBConnectException;
import com.mongodb.Mongo;
import com.mongodb.ServerAddress;
import com.mongodb.gridfs.GridFS;

public class MongoDBManager {
	private Logger logger = LoggerFactory.getLogger(MongoDBManager.class);

	private String avataDB;// 头像数据库
	private Mongo mongo;
	

	@SuppressWarnings("deprecation")
	public MongoDBManager(String host, int port) throws DBConnectException {
		try {
			mongo = new Mongo(new ServerAddress(host, port));// 连接池参数按照mongo默认设置，如果想自定义，可以配置MongoOptions传到mongo构造函数中
			logger.debug("MongoDBManager constructor success");
		} catch (UnknownHostException e) {
			logger.error("mongoDB connection failed", e);
			throw new DBConnectException();
		}
	}

	public GridFS getAvataGridFs() {
		return new GridFS(mongo.getDB(avataDB));
	}

	public void close() {
		if (null != mongo) {
			mongo.close();
			logger.debug("mongoDB close success");
		}
	}

	public void setAvataDB(String avataDB) {
		this.avataDB = avataDB;
	}

}
